package com.zmm.weblog.web.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.zmm.weblog.common.domain.dos.ArticleDo;
import com.zmm.weblog.common.domain.mapper.ArticleMapper;
import com.zmm.weblog.common.utils.PageResponse;
import com.zmm.weblog.common.utils.Response;
import com.zmm.weblog.web.convert.ArticleConvert;
import com.zmm.weblog.web.module.vo.archive.FindArchiveArticlePageListReqVo;
import com.zmm.weblog.web.module.vo.archive.FindArchiveArticlePageListRspVo;
import com.zmm.weblog.web.module.vo.archive.FindArchiveArticleRspVo;
import com.zmm.weblog.web.service.ArchiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.YearMonth;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @Author: 福禄寿
 * @Date: 2024/8/6 下午5:39
 * @Des: weblog-springboot
 **/
@Service
public class ArchiveServiceImpl implements ArchiveService {


    @Autowired
    private ArticleMapper articleMapper;
    /**
     * 获取文章归档分页数据
     * @param findArchiveArticlePageListReqVo
     * @return
     */
    @Override
    public Response findArchivePageList(FindArchiveArticlePageListReqVo findArchiveArticlePageListReqVo) {
        Long current = findArchiveArticlePageListReqVo.getCurrent();
        Long size = findArchiveArticlePageListReqVo.getSize();

        IPage<ArticleDo> page = articleMapper.selectPageList(current, size, null, null, null);
        List<ArticleDo> articleDos = page.getRecords();
        List<FindArchiveArticlePageListRspVo> vos = Lists.newArrayList();
        if (articleDos != null && articleDos.size() > 0) {
            List<FindArchiveArticleRspVo> archiveArticleRspVos = articleDos.stream().map(articleDO ->
                            ArticleConvert.INSTANCE.convertDO2ArchiveVO(articleDO))
                    .collect(Collectors.toList());
            Map<YearMonth, List<FindArchiveArticleRspVo>> map = archiveArticleRspVos.stream().collect(Collectors.groupingBy(FindArchiveArticleRspVo::getCreateMonth));
            TreeMap<YearMonth, List<FindArchiveArticleRspVo>> sortedMap = new TreeMap<>(Collections.reverseOrder());
            sortedMap.putAll(map);
            //vos.add(FindArchiveArticlePageListRspVo.builder().month(sortedMap.firstKey()).articles(sortedMap.get(sortedMap.firstKey())).build());
            sortedMap.forEach((k, v) -> vos.add(FindArchiveArticlePageListRspVo.builder().month(k).articles(v).build()));
        }
        return PageResponse.success(page, vos);
    }
}
